<?php
/**
 * DownGoods.php class file.
 * @author wudg <544038230@qq.com>
 * @date 2020/12/27- 下午5:40
 */

namespace common\jobs\sync;


use common\constants\ProductConst;
use common\jobs\dao\PddCopyProductsDao;
use common\jobs\models\PddMallProduct;
use common\components\api\isv\Goods;
use common\exception\JobException;
use console\components\helpers\ConsoleHelper;
use common\constants\SyncConst;
use common\dao\PddSyncLogDao;
use common\exception\ServicesException;
use common\exception\ValidatorException;
use common\services\SyncService;
use yii\db\Exception;
use Yii;

class SyncGoodsToDetail extends SyncBase implements \common\drivers\interfaces\JobInterface
{
    public $args = [];


    /**
     * 获取异步任务执行需要的参数
     * SyncProduct constructor.
     * @param array $args
     */
    public function __construct(array $args = [])
    {
        $this->args = $args;

        $this->cacheSuccessKey .= $this->args['log_id'];
        $this->cacheErrorKey .= $this->args['log_id'];
        $this->totalCacheKey .= $this->args['log_id'];
    }



    /**
     * 处理队列
     * @return mixed|void
     */
    public function handle() :void
    {
        try {
            Yii::$app->db->open();
            $goodsDetail = (new Goods())->pddGoodsDetailGet($this->args['goods_id'],$this->args['mall_id']);
            if(isset($goodsDetail) && count($goodsDetail))
            {
                $timestamp = time();
                $insertProduct = [];
                /**
                 * 关联下是否是从本软件搬家商品
                 */
                $logInfo = (new PddCopyProductsDao())->getInfoByCopyIdAndMallId($this->args['goods_id'],$this->args['mall_id']);
                if($logInfo) {
                    ConsoleHelper::runInfo($this->args['goods_id'].'->匹配到搬家日志:'.$logInfo->num_iid.',平台ID:'.$logInfo->platform);
                    $insertProduct['copy_source_type'] = $logInfo->platform;
                    $insertProduct['copy_source_id'] = $logInfo->num_iid;
                    $insertProduct['is_copy'] = 1;
                }else{
                    $insertProduct['copy_source_type'] = 0;
                    $insertProduct['copy_source_id'] = '';
                    $insertProduct['is_copy'] = 0;
                }
                $insertProduct['goods_id'] = $goodsDetail['goods_id'];
                $insertProduct['mall_id'] = $this->args['mall_id'];
                $insertProduct['uid'] =  $this->args['uid'];
                $insertProduct['goods_sn'] = $goodsDetail['goods_sn'] ?? '';
                $insertProduct['outer_goods_id'] = $goodsDetail['outer_goods_id'] ?? '';
                $insertProduct['out_source_goods_id'] = $goodsDetail['out_source_goods_id'] ?? '';
                $insertProduct['out_source_type'] = $goodsDetail['out_source_type'] ?? '';
                $insertProduct['goods_type'] = $goodsDetail['goods_type'] ?? 0;
                $insertProduct['cat_id'] = $goodsDetail['cat_id'];
                $insertProduct['country_id'] = $goodsDetail['country_id'] ?? 0;
                $insertProduct['invoice_status'] = $goodsDetail['invoice_status'] ?? 0;
                $insertProduct['is_folt'] = $goodsDetail['is_folt'] ?? 0;
                $insertProduct['second_hand'] = $goodsDetail['second_hand'] ?? 0;
                $insertProduct['quan_guo_lian_bao'] = $goodsDetail['quan_guo_lian_bao'] ?? 0;
                $insertProduct['is_pre_sale'] = $goodsDetail['is_pre_sale'] ?? 0;
                $insertProduct['pre_sale_time'] = $goodsDetail['pre_sale_time'] ?? 0;
                $insertProduct['delivery_type'] = $goodsDetail['delivery_type'] ?? 1;
                $insertProduct['is_refundable'] = $goodsDetail['is_refundable'] ?? 0;
                $insertProduct['shipment_limit_second'] = $goodsDetail['shipment_limit_second'] ?? 0;
                $insertProduct['market_price'] = $goodsDetail['market_price'];
                $insertProduct['goods_name'] = $goodsDetail['goods_name'];
                $insertProduct['tiny_name'] = $goodsDetail['tiny_name'] ?? '';
                $insertProduct['status'] = $goodsDetail['status'] ?? 0;
                $insertProduct['order_limit'] = $goodsDetail['order_limit'] ?? 0;
                $insertProduct['image_url'] = $goodsDetail['thumb_url'] ?? ''; //取商品缩略图
                $insertProduct['delivery_one_day'] = $goodsDetail['delivery_one_day'] ?? 0;
                $insertProduct['cost_template_id'] = $goodsDetail['cost_template_id'] ?? 0;
                $insertProduct['bad_fruit_claim'] = $goodsDetail['bad_fruit_claim'] ?? 0;
                $insertProduct['buy_limit'] = $goodsDetail['buy_limit'] ?? 0;
                $insertProduct['goods_desc'] = $goodsDetail['goods_desc'] ?? '';
                $insertProduct['customer_num'] = $goodsDetail['customer_num'] ?? 0;
                $insertProduct['video_gallery'] = json_encode($goodsDetail['video_gallery'],JSON_UNESCAPED_UNICODE) ?? json_encode([]);
                $insertProduct['carousel_gallery_list'] = json_encode($goodsDetail['carousel_gallery_list'],JSON_UNESCAPED_UNICODE) ?? json_encode([]);
                $insertProduct['detail_gallery_list'] = json_encode($goodsDetail['detail_gallery_list'],JSON_UNESCAPED_UNICODE) ?? json_encode([]);
                $insertProduct['goods_property_list'] = json_encode($goodsDetail['goods_property_list'],JSON_UNESCAPED_UNICODE) ?? json_encode([]);
                $insertProduct['goods_trade_attr'] = !empty($goodsDetail['goods_trade_attr']) ? json_encode($goodsDetail['goods_trade_attr'],JSON_UNESCAPED_UNICODE) : json_encode([]);
                $insertProduct['goods_travel_attr'] = !empty($goodsDetail['goods_travel_attr']) ? json_encode($goodsDetail['goods_travel_attr'],JSON_UNESCAPED_UNICODE) : json_encode([]);
                $insertProduct['sync_at'] = $timestamp;
                $insertProduct['goods_quantity'] = 0;

                $insertSkus = [];

                $skuPrice = [];
                if(isset($goodsDetail['sku_list']) && count($goodsDetail['sku_list']))
                {
                    foreach($goodsDetail['sku_list'] as $s => $sku)
                    {
                        $tmpSku = [];
                        $tmpSku['sku_id'] = $sku['sku_id'];
                        $tmpSku['goods_id'] = $goodsDetail['goods_id'];
                        $tmpSku['is_onsale'] = $sku['is_onsale'] ?? 0;
                        $tmpSku['thumb_url'] = $sku['thumb_url'] ?? '';
                        $tmpSku['length'] = $sku['length'] ?? 0;
                        $tmpSku['multi_price'] = $sku['multi_price'] ?? 0;
                        $tmpSku['price'] = $sku['price'] ?? 0;
                        $tmpSku['weight'] = $sku['weight'] ?? 0;
                        $tmpSku['limit_quantity'] = $sku['limit_quantity'] ?? 0;
                        $tmpSku['out_sku_sn'] = $sku['out_sku_sn'] ?? '';
                        $tmpSku['spec'] =json_encode($sku['spec'],JSON_UNESCAPED_UNICODE) ?? json_encode([]);
                        $tmpSku['oversea_sku'] =!empty($sku['oversea_sku']) ? json_encode($sku['oversea_sku'],JSON_UNESCAPED_UNICODE) : json_encode([]);
                        $tmpSku['out_source_sku_id'] = $sku['out_source_sku_id'] ?? '';
                        $tmpSku['quantity'] = $sku['quantity'] ?? 0;
                        $insertProduct['goods_quantity'] += $sku['quantity'];
                        $tmpSku['sync_at'] = $timestamp;
                        array_push($skuPrice,$sku['multi_price']);
                        array_push($insertSkus,$tmpSku);
                    }
                }
                $insertProduct['sale_price'] = min($skuPrice);
                $result =  (new SyncService())->syncProducts($insertProduct,$insertSkus);
                if($result)
                {
                    $this->setSuccessNum();
                    ConsoleHelper::runInfo('成功同步商goods_id:'.$goodsDetail['goods_id']);
                }else{
                    $this->setErrorNum();
                }
            }
            Yii::$app->db->close();
        }catch (ValidatorException $e)
        {
            $this->setErrorNum();
            throw new JobException($e->getMessage());
        }catch (ServicesException $e)
        {
            $this->setErrorNum();
            throw new JobException($e->getMessage());
        }catch (Exception $e)
        {
            $this->setErrorNum();
            throw new JobException($e->getMessage());
        }catch (\yii\base\Exception $e)
        {
            $this->setErrorNum();
            throw new JobException($e->getMessage());
        } finally {
            Yii::$app->db->close();
        }
    }

    /**
     * @throws \yii\base\Exception
     */
    protected function setSuccessNum()
    {
        $cacheSuccessNum = Yii::$app->redis->get($this->cacheSuccessKey);
        if(!$cacheSuccessNum)
        {
            Yii::$app->redis->setex($this->cacheSuccessKey,86400,1);
        }else{
            Yii::$app->redis->incr($this->cacheSuccessKey);
        }
        $this->upsetBatchInfo();
    }

    protected function getSuccessNum()
    {
        return  Yii::$app->redis->get($this->cacheSuccessKey);
    }


    /**
     * @throws \yii\base\Exception
     */
    protected function setErrorNum()
    {
        $cacheErrorNum = Yii::$app->redis->get($this->cacheErrorKey);
        if(!$cacheErrorNum)
        {
            Yii::$app->redis->setex($this->cacheErrorKey,86400,1);
        }else{
            Yii::$app->redis->incr($this->cacheErrorKey);
        }
        $this->upsetBatchInfo();
    }


    protected function getErrorNum()
    {
        return  Yii::$app->redis->get($this->cacheErrorKey);
    }


    /**
     * @throws \yii\base\Exception
     */
    protected function upsetBatchInfo()
    {
        $successNum = (int)$this->getSuccessNum();
        $errorNum = (int)$this->getErrorNum();
        $totalNum = $successNum + $errorNum;
        $total_cnt = Yii::$app->redis->get($this->totalCacheKey);
        if($totalNum == $total_cnt)
        {

            $syncLog = (new PddSyncLogDao())->getInfoByPk($this->args['log_id']);
            $syncLog->suc_cnt = $successNum;
            $syncLog->total_cnt = $total_cnt;
            $syncLog->err_cnt = $errorNum;
            $syncLog->status = SyncConst::SYNC_STATUS_YES;
            $syncLog->save();
            //历史同步的商品全部设置为删除状态
            if($syncLog->sync_type == 1){
                PddMallProduct::updateAll(['status' => ProductConst::IS_DEL],'mall_id = '.$this->args['mall_id'].' AND uid = '.$this->args['uid'].' AND sync_at < '.$syncLog->sync_at);
            }


//            $ids = PddMallProduct::find()->select(['goods_id'])->where([
//                'mall_id' => $this->args['mall_id'],
//                'uid' => $this->args['uid']
//            ])->andFilterWhere(['<','sync_at',$syncLog->sync_at])
//                ->asArray()->all();

//            $syncEsService = new SyncEsService();
//            $syncEsService->syncMallProduct($ids);
            Yii::$app->redis->del($this->cacheErrorKey);
            Yii::$app->redis->del($this->totalCacheKey);
            Yii::$app->redis->del($this->cacheSuccessKey);
        }
    }
}